<?php
global $_GPC, $_W;
$GLOBALS['frames'] = $this->getMainMenu();
$branch_list = pdo_getall('yzzc_sun_branch',['uniacid'=>$_W['uniacid']],['id','name']);
$distribution_list = pdo_getall('yzzc_sun_distribution_promoter',['uniacid'=>$_W['uniacid'],'status' => 1],['uid','name']);
$shuttle_list = pdo_getall('yzzc_sun_shuttle',['uniacid'=>$_W['uniacid']],['id','name']);
$store_list = pdo_getall('yzzc_sun_store',['uniacid'=>$_W['uniacid']],['store_id','name']);

$where = "where o.uniacid =" . $_W['uniacid'];
$keywords = $_GPC['keywords'] ?? '';
if ($keywords) {
//    $where .= " and (o.username LIKE  '%$keywords%' or o.tel LIKE  '%$keywords%' or o.ordernum LIKE  '%$keywords%' or o.carnum LIKE '%$keywords%')";
    $where .= " and (o.ordernum LIKE  '%$keywords%' or o.carnum LIKE  '%$keywords%' or o.shuttle_name LIKE  '%$keywords%' or o.reclaim_shuttle_name LIKE  '%$keywords%')";
}
$branch_id = $_GPC['branch_id'] ?? '';
if ($branch_id){
    $where.= " and o.start_shop =".$branch_id;
}

$range_time = $_GPC['range_time'] ?? [];
$start_time = $end_time = '';
if ($range_time['start'] && $range_time['end']) {
    $start_time = $range_time['start'];
    $end_time = $range_time['end'];
    $end_time = strtotime($end_time);
    $start_time = strtotime($start_time);
    $where.=' and o.createtime > '.$start_time .' and o.createtime<='.$end_time;
}

$distribution_id = $_GPC['distribution_id'] ?? '';
if ($distribution_id){
    $where.=' and o.distribution_id = '.$distribution_id;
}

//$shuttle_id = $_GPC['shuttle_id'] ?? '';
//if ($shuttle_id){
//    $where.=' and o.shuttle_id = '.$shuttle_id;
//}

$store_id = $_GPC['store_id'] ?? '';
if ($store_id){
    $where.=' and o.store_id = '.$store_id;
}

$page = max(1, intval($_GPC['page']));
$size = intval($_GPC['psize']) ? intval($_GPC['psize']) : 10;
$sql = 'SELECT o.distribution_id,o.start_shop,o.id,o.store_id,o.reclaim_shuttle_name,o.is_onsite,o.shuttle_id,o.shuttle_commission,o.total_money,o.createtime,o.car_name,o.carnum,b.name as branch_name FROM ' . tablename('yzzc_sun_order') . " o left join ".tablename('yzzc_sun_branch')." b on b.id=o.start_shop  {$where} ORDER BY o.id DESC LIMIT " . (($page - 1) * $size) . ',' . $size;

//$sql = 'SELECT * FROM ' . tablename('yzzc_sun_order_fees') . " {$where} ORDER BY id DESC LIMIT " . (($page - 1) * $size) . ',' . $size;
$info = pdo_fetchall($sql);
$total_money = $distribution_total = $shuttle_total = $store_total = $branch_total = 0;
if ($info){
    foreach ($info as $key => $value){
        //经办人
        $distribution_name = '';
        $distribution_order_count = 0;
        if ($value['distribution_id']){
            $distribution_name = pdo_fetchcolumn('select name from '.tablename('yzzc_sun_distribution_promoter').' where uid = :id', ['id' => $value['distribution_id']]);
            $distribution_order_count = pdo_fetchcolumn('select first_price from '.tablename('yzzc_sun_distribution_order').' where parent_id_1 = :id AND order_id = :order_id', ['id' => $value['distribution_id'],'order_id' => $value['id']]);
        }
        $info[$key]['distribution_name'] = $distribution_name;
        $info[$key]['distribution_order_total'] = $distribution_order_count;

        //门店
        $branch_amount = pdo_fetchcolumn('select amount from '.tablename('yzzc_sun_branch_income').' where  order_id = :order_id AND branch_id = :branch_id', ['branch_id' => $value['start_shop'],'order_id'=>$value['id']]);
        $info[$key]['branch_total'] = $branch_amount;

        //个人车主
        $store_name = '';
        $store_total = 0;
        if ($value['store_id'] > 0){
            $store_amount = pdo_fetchcolumn('select amount from '.tablename('yzzc_sun_store_income').' where store_id = :store_id AND order_id = :order_id', ['store_id' => $value['store_id'],'order_id'=>$value['id']]);
            $store_name = pdo_fetchcolumn('select name from '.tablename('yzzc_sun_store').' where store_id = :store_id', ['store_id' => $value['store_id']]);
        }
        $info[$key]['store_total'] = $store_amount;
        $info[$key]['store_name'] = $store_name;

        //送车员
        $shuttle_name = '';
        if ($value['shuttle_id'] > 0){
            $shuttle_name = pdo_fetchcolumn('select name from '.tablename('yzzc_sun_shuttle').' where id = :id', ['id' => $value['shuttle_id']]);
        }
        $info[$key]['shuttle_name'] = $shuttle_name;
        $info[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
    }
    //统计
    $total_sql = 'SELECT o.distribution_id,o.start_shop,o.id,o.store_id,o.shuttle_id,o.shuttle_commission,o.total_money FROM ' . tablename('yzzc_sun_order') . " as o  {$where} ";
    $total_info = pdo_fetchall($total_sql);
    foreach ($total_info as $key => $value){
        //经办人
        $distribution_order_count = 0;
        if ($value['distribution_id']){
            $distribution_order_count = pdo_fetchcolumn('select first_price from '.tablename('yzzc_sun_distribution_order').' where parent_id_1 = :id AND order_id = :order_id', ['id' => $value['distribution_id'],'order_id' => $value['id']]);
        }
        $distribution_total+=$distribution_order_count;

        //门店
        $branch_amount = pdo_fetchcolumn('select amount from '.tablename('yzzc_sun_branch_income').' where order_id = :order_id AND branch_id = :branch_id', ['branch_id' => $value['start_shop'],'order_id'=>$value['id']]);
        $branch_total+=$branch_amount;

        //个人车主
        $store_amount = 0;
        if ($value['store_id'] > 0){
            $store_amount = pdo_fetchcolumn('select amount from '.tablename('yzzc_sun_store_income').' where store_id = :store_id AND order_id = :order_id', ['store_id' => $value['store_id'],'order_id'=>$value['id']]);
        }
        $store_total+=$store_amount;

        //送车员
        $shuttle_name = '';
        if ($value['shuttle_id'] > 0){
            $shuttle_name = pdo_fetchcolumn('select amount from '.tablename('yzzc_sun_shuttle').' where shuttle_id = :id', ['id' => $value['shuttle_id']]);
        }
        $shuttle_total+= $value['shuttle_commission'];
        //总收入
        $total_money += $value['total_money'];
    }
}

$total = pdo_fetchcolumn("select count(*) from " . tablename("yzzc_sun_branch_income") . " where uniacid =" . $_W['uniacid']);
$pager = pagination($total, $page, $size);

//导出
if ($_GPC['op'] == 'export_order') {
    $where = "where f.uniacid =" . $_W['uniacid'];
    $keywords = $_GPC['keywords'] ?? '';
    if ($keywords) {
//    $where .= " and (o.username LIKE  '%$keywords%' or o.tel LIKE  '%$keywords%' or o.ordernum LIKE  '%$keywords%' or o.carnum LIKE '%$keywords%')";
        $where .= " and (f.order_num LIKE  '%$keywords%' or f.car_num LIKE  '%$keywords%')";
    }
    $branch_id = $_GPC['branch_id'] ?? '';
    if ($branch_id){
        $where.= " and f.branch_id=".$branch_id;
    }

    $range_time = $_GPC['range_time'] ?? [];
    $start_time = $_GPC['start_time'] ?? '';
    $end_time = $_GPC['end_time'] ?? '';
    if ($end_time && $start_time) {
        $end_time = strtotime($end_time);
        $start_time = strtotime($start_time);
        $where.=' and f.createtime > '.$start_time .' and f.createtime<='.$end_time;
    }

    $distribution_id = $_GPC['distribution_id'] ?? '';
    if ($distribution_id){
        $where.=' and o.distribution_id = '.$distribution_id;
    }

    $shuttle_id = $_GPC['shuttle_id'] ?? '';
    if ($shuttle_id){
        $where.=' and o.shuttle_id = '.$shuttle_id;
    }
    $sql = 'SELECT f.*,s.name as shuttle_name,o.day,o.start_time as order_start_time,o.end_time as order_end_time,o.username,o.money,o.total_money,o.distribution_id FROM ' . tablename('yzzc_sun_order_fees') . " f left join ".tablename('yzzc_sun_order')." o on o.id=f.order_id  left join ".tablename('yzzc_sun_shuttle')." s on s.id=o.shuttle_id {$where} ORDER BY f.id ";
//    $sql = 'SELECT b.name as branch_name,sd.km_start,sd.km_end,sd.delivery_start_time,sd.delivery_end_time,sd.petrol_start,sd.petrol_end,sd.deposit,sd.give_car_cost,sd.reclaim_car_cost,sd.security,sd.refund_deposit,sd.deposit,sd.refund_security,sd.exceed_km,sd.exceed_time,sd.gasoline_subsidy_cost,sd.peccant_cost,sd.car_damage_cost,sd.repair_cost,sd.intermediary_cost,sd.driver_cost,sd.refueling_cost,sd.maintenance_cost,s.name as shuttle_name,o.* FROM ' . tablename('yzzc_sun_order') . " o left join ".tablename('yzzc_sun_branch')." b on b.id=o.start_shop  left join ".tablename('yzzc_sun_shuttle_delivery')." sd on sd.order_id = o.id  left join ".tablename('yzzc_sun_shuttle')." s on s.id=sd.shuttle_id {$where} ORDER BY o.id DESC ";
    $info = pdo_fetchall($sql);

    $export_title_str = "门店,车牌,客户,送车人,经办人,租金/天,租期,开始时间,结束时间,公里数(起),公里数(止),油量(起),油量(止),交车时间,还车时间,保证金,退押金,租金,超公里,超时,司机,送/收车费,油补,违章,车损,维修费,应收金额,调入调出,超公里,中介,司机费用,报销,加油,违章,维修保养,费用合计,实际收入,利润,差异,备注,创建时间";
    $export_title = explode(',', $export_title_str);
    $i = 1;
    $export_list = [];
    foreach ($info as $key => $value){
        $distribution_name = '';
        if ($value['distribution_id']){
            $distribution_name = pdo_fetchcolumn('select name from '.tablename('yzzc_sun_distribution_promoter').' where id = :id', ['id' => $value['distribution_id']]);
        }


        $arr = [
            'branch_name' => $value['branch_name']. "\t",
//            'car_name' => $value['car_name']. "\t",
            'car_num' => $value['car_num']. "\t",

            'username' => $value['username']. "\t",
            'shuttle_name' => $value['shuttle_name']. "\t",
            'distribution_name' => $distribution_name. "\t",
            'car_money' => $value['money']. "\t",
            'day' => $value['day']. "\t",
            'order_start_time' => date('Y-m-d',$value['order_start_time']). "\t",
            'order_end_time' => date('Y-m-d',$value['order_end_time']). "\t",
            'km_start' => $value['km_start']. "\t",
            'km_end' => $value['km_end']. "\t",
            'petrol_start' => $value['petrol_start']. "\t",
            'petrol_end' => $value['petrol_end']. "\t",
            'start_time' => $value['start_time']. "\t",
            'end_time' => $value['end_time']. "\t",

            'security' => $value['security']. "\t",
            'refund_deposit' => $value['refund_deposit']. "\t",
            'total_money' => $value['total_money']. "\t",

            'exceed_km' => $value['exceed_km']. "\t",
            'exceed_time' => $value['exceed_time']. "\t",
            'driver_revenue' => $value['driver_revenue']. "\t",
            'give_revenue' => $value['give_revenue']. "\t",
            'gasoline_subsidy_revenue' => $value['gasoline_subsidy_revenue']. "\t",
            'peccant_revenue' => $value['peccant_revenue']. "\t",
            'car_damage_revenue' => $value['car_damage_revenue']. "\t",
            'repair_revenue' => $value['repair_revenue']. "\t",
            'total_revenue' => $value['total_revenue']. "\t",
            'callout_cost' => $value['callout_cost']. "\t",
            'exceed_km_cost' => $value['exceed_km_cost']. "\t",
            'intermediary_cost' => $value['intermediary_cost']. "\t",
            'driver_cost' => $value['driver_cost']. "\t",
            'reimbursement_cost' => $value['reimbursement_cost']. "\t",
            'refueling_subsidies_cost' => $value['refueling_subsidies_cost']. "\t",
            'peccancy_cost' => $value['refueling_subsidies_cost']. "\t",
            'maintenance_cost' => $value['maintenance_cost']. "\t",

            'total_cost' => $value['total_cost']. "\t",
            'paid_cost' => $value['paid_cost']. "\t",
            'profit_cost' => $value['profit_cost']. "\t",
            'difference_cost' => $value['difference_cost']. "\t",
            'remark' => $value['remark']. "\t",
            'create_time' => date('Y-m-d H:i:s',$value['createtime']). "\t",
        ];
        $export_list[] = $arr;
        $i++;
    }
    exportToExcel('车辆收益' . '_' . date("YmdHi") . '.csv', $export_title, $export_list);
    exit;
}

//导出方法
/**
 * @creator Jimmy
 * @data 2018/1/05
 * @desc 数据导出到excel(csv文件)
 * @param $filename 导出的csv文件名称 如'test-'.date("Y年m月j日").'.csv'
 * @param array $tileArray 所有列名称
 * @param array $dataArray 所有列数据
 */
function exportToExcel($filename, $tileArray = array(), $dataArray = array())
{
    ini_set('memory_limit', '512M');
    ini_set('max_execution_time', 0);
    ob_end_clean();
    ob_start();
    header("Content-Type: text/csv");
    header("Content-Disposition:filename=" . $filename);
    $fp = fopen('php://output', 'w');
    fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
    fputcsv($fp, $tileArray);
    $index = 0;
    foreach ($dataArray as $item) {
        $index++;
        fputcsv($fp, $item);
    }

    ob_flush();
    flush();
    ob_end_clean();
}

/*if ($_GPC['op'] == 'income'){
    $branch_id = $_GPC['id'];
    $range_time = $_GPC['range_time'] ?? [];
    $where = 'i.status= 1 and i.branch_id='.$branch_id;
    $start_time = $end_time = '';
    if ($range_time){
        $start_time = $range_time['start'];
        $end_time = $range_time['end'];
        $end_time = strtotime($end_time);
        $start_time = strtotime($start_time);
        $where.=' and i.createtime > '.$start_time .' and i.createtime<='.$end_time;
    }

    $branch_info = pdo_get('yzzc_sun_branch',['uniacid'=>$_W['uniacid'],'id'=>$branch_id],['id','name']);
    $sql = 'SELECT i.id,i.total,i.type,i.platform_fee,i.branch_id,i.amount,i.status,i.createtime,o.ordernum,o.username,o.tel FROM ' . tablename('yzzc_sun_branch_income') . " i left join ".tablename('yzzc_sun_order')." o on i.order_id=o.id where  {$where} ORDER BY i.createtime DESC";

    $info = pdo_fetchall($sql);
    if ($info){
        foreach ($info as $key => $value){
            foreach ($branch_list as $val){
                if ($value['branch_id'] == $val['id']){
                    $info[$key]['branch_name'] = $val['name'];
                }
            }
            $info[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
        }
    }
    include $this->template('web/branch_store_income');
    return;
}
if ($_GPC['op'] == 'branch_income'){
    $branch_id = $_GPC['branch_id'];
    $range_time = $_GPC['range_time'] ?? [];
    $where = 'status= 1 and branch_id='.$branch_id;
    $type = $_GPC['type'];
    if ($type !== 'all'){
        $start_time = $_GPC['start_time'];
        $end_time = $_GPC['end_time'];
        $end_time = strtotime($end_time);
        $start_time = strtotime($start_time);
        $where.=' and createtime > '.$start_time .' and createtime<='.$end_time;
    }
    $branch_info = pdo_get('yzzc_sun_branch',['uniacid'=>$_W['uniacid'],'id'=>$branch_id],['id','name','balance']);
    $sql = 'SELECT * FROM ' . tablename('yzzc_sun_branch_income') . " where {$where}";

    $info = pdo_fetchall($sql);
    if (!$info){
        message('暂无结算收益','','error');
    }
    $price = 0;
    foreach ($info as $value){
        $price+=$value['amount'];
    }

    $branch_update = pdo_update('yzzc_sun_branch',['balance' => $branch_info['balance'] + $price],['uniacid'=>$_W['uniacid'],'id'=>$branch_id]);
    $update_sql = 'UPDATE ' . tablename('yzzc_sun_branch_income') . " set status= 2,income_time = ".time()." where {$where}";
    $income_update = pdo_query($update_sql);
    if ($branch_update && $income_update){
        message('结算成功','','success');
    }
    message('结算失败，请联系管理员','','error');
}
if ($_GPC['op'] == 'change') {
    if ($_GPC['states'] == 2) {
        $is = pdo_get('yzzc_sun_goods', array('sid' => $_GPC['id'], 'status' => 1));
        if ($is) {
            message('请先至车辆列表下架所有车辆才能停业', '', 'error');
        }
    }

    $res = pdo_update('yzzc_sun_branch', array('status' => $_GPC['states']), array('id' => $_GPC['id']));
    if ($res) {
        message('操作成功', $this->createWebUrl('branchslist', array()), 'success');
    } else {
        message('操作失败', '', 'error');
    }
}*/

include $this->template('web/order_role_income');